const fs = require('fs');
const fsExtra = require('fs-extra');
const compressing = require('compressing');
const path = require('path');

const DataTypes = ['HEART_RATE', 'STEP_COUNT', 'SPO2', 'STRESS']

const isValidDataType = (dataType) => DataTypes.includes(dataType)

function makeComp({ background, title, desc, size, dataType, initData }) {
  const typeValue = isValidDataType(dataType) ? '{{typeValue}}' : (initData || '--')
  
  return `
    <stack class="card size-${size}">
      <image class="card-img size-${size}" src="/watch3001/assets/${background}"></image>
      <div class="card-inner size-${size}">
        <text class="card-title">${title}</text>
        <text class="card-value">${typeValue}</text>
        <text class="card-desc">${desc}</text>
      </div>
    </stack>
  `
}

function replaceAIContent(inputStr, replacement) {
  // 正则表达式，匹配 <!-- AI内容start --> 和 <!-- AI内容end --> 之间的所有内容
  const regex = /<!-- AI内容start -->[\s\S]*?<!-- AI内容end -->/g;
  // 替换匹配到的内容
  return inputStr.replace(regex, `<!-- AI内容start -->${replacement}<!-- AI内容end -->`);
}


// 设置运动类型
function setDataType(inputStr, dataType) {
  if (isValidDataType(dataType)) {
    return inputStr.replace("const __DATA_TYPE__ = 'HEART_RATE'", `const __DATA_TYPE__ = '${dataType}'`)
  }
  return inputStr
}

exports.create = function (filePath, outFilePath, tempProjectDest, outPutProjectDest, cardJsonPath, outPutDist) {
  fsExtra.copySync(tempProjectDest, outPutProjectDest)
  try {
    const cardJson = fsExtra.readJSONSync(cardJsonPath)
    console.log(cardJson)
    const data = fs.readFileSync(filePath, 'utf8');
    const outputUx = replaceAIContent(data, makeComp(cardJson))
    const outputWithDataType = setDataType(outputUx, cardJson.dataType)
    fs.writeFileSync(outFilePath, outputWithDataType, 'utf8');
    compressing.zip.compressDir(outPutProjectDest, path.resolve(outPutDist, cardJson.pkgName))
    console.log(`生成成功 ${path.resolve(outPutDist, cardJson.pkgName)}`)
  } catch (err) {
    console.error('读取文件时发生错误:', err);
  }
}